<template>
    <div class="bg-f2f3f5 leaveSpace">
        <div class="flex max-w-1200 mar-x-auto pad-y-10">
            <div class="flex-1 bg-white border-rad-5" style="height: calc(100vh - 91px)">
                <div class="mar-x-10 mar-t-10">
                    <div class="vanish_items text-nowrap flex gap-10 justify-between align-center">
                        <div class="color-1e9fff font-18">^_^创作属于你的文章吧!</div>

                        <div class="flex">
                            <div
                                class="draft mar-r-10 color-white border-rad-3 pad-y-5 pad-x-10 bg-c6c6c6"
                                @click="showClassifyDialog(0)"
                            >
                                <span>保存至草稿箱</span>
                            </div>

                            <div class="publish bg-1e9fff color-white border-rad-3 pad-y-5 pad-x-10 b-1-solid-1e80ff" @click="showClassifyDialog(1)">
                                <span>发布</span>
                            </div>
                        </div>
                    </div>

                    <div class="appear_items text-nowrap align-center">
                        <div class="color-1e9fff font-18">^_^创作属于你的文章吧!</div>

                        <div class="flex mar-t-10 justify-end">
                            <div
                                class="draft mar-r-10 color-white border-rad-3 pad-y-5 pad-x-10 bg-c6c6c6"
                                @click="showClassifyDialog(0)"
                            >
                                <span>保存至草稿箱</span>
                            </div>

                            <div class="publish bg-1e9fff color-white border-rad-3 pad-y-5 pad-x-10 b-1-solid-1e80ff" @click="showClassifyDialog(1)">
                                <span>发布</span>
                            </div>
                        </div>
                    </div>

                    <input type="text"
                        placeholder="输入文章标题..."
                        v-model="classifyDialog.title"
                        class="input-init title"
                    >
                </div>

                <div class="mar-x-10">
                    <quill-editor
                        class="editor"
                        v-model="classifyDialog.content"
                        ref="myQuillEditor"
                        :options="editorOption"
                        @blur="onEditorBlur($event)"
                        @focus="onEditorFocus($event)"
                        @ready="onEditorReady($event)"
                        @change="onEditorChange($event)"
                    ></quill-editor>
                </div>
            </div>

            <div class="vanish_items flex-1 mar-15">
                <div v-html="previewHtml" class="ql-snow w-100"></div>
                <div v-if="!classifyDialog.content" class="color-999999">预览内容</div>
            </div>
        </div>
        
        <ClassifyDialog
            v-if="dialogVisible"
            :articleId="articleId"
            :classifyDialog="classifyDialog"
            :dialogVisible="dialogVisible"
            :classifyList="classifyList"
            @cancelClassifyDialog="cancelClassifyDialog"
            @confirmClassifyDialog="confirmClassifyDialog"
        />
    </div>
</template>

<script>
    import Utils from '@/utils/utils'
    import imageResize  from 'quill-image-resize-module'
    import ClassifyDialog from '@/components/CenterPersonal/ArticleManage/ClassifyDialog'

    import { quillEditor, Quill } from 'vue-quill-editor'
    import { checkLogin } from'@/utils/lib'
    import { ImageDrop } from 'quill-image-drop-module'
    Quill.register('modules/imageResize', imageResize )
    Quill.register('modules/imageDrop', ImageDrop)

    import { mapState } from 'vuex'
    import { uploadFile } from '@/apis/common'
    import { getClassifyList, addArticle, getArticleDetail, updateArticle } from '@/apis/article'

    export default {
        name: 'StartCreating',

        components: {
            quillEditor,
            ClassifyDialog,
        },

        computed: {
            ...mapState({
                userInfo: state => state.user.userInfo, // 用户信息
                currentMenuId: state => state.articleManage.currentMenuId, // 当前菜单id
            })
        },

        data() {
            return {
                articleId: null, // 文章id
                details: null, // 文章详情
                pageLoading: false, // 页面加载控制
                dialogVisible: false, // 弹窗控制
                previewHtml: '', // 预览html
                classifyList: [], // 分类列表
                // 分类弹窗数据
				classifyDialog: {
					title: '', // 标题
                	content: '', // 文章内容
					classifyId: '', // 分类id
					abstract: '', // 摘要
                    coverUrl: '', // 封面图片
					state: 0, // 0 草稿，1 待审核(发布)
				},

                // 富文本配置
                editorOption: {
                    modules: {
                        toolbar: {
                            container: [
                                ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
                                [{ 'list': 'ordered'}, { 'list': 'bullet' }], // 有序，无序列表
                                [{ 'indent': '-1'}, { 'indent': '+1' }], // 缩进
                                [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
                                [{ 'header': [1, 2, 3, 4, 5, 6, false] }], // 标题
                                [{ 'color': [] }, { 'background': [] }], // 字体颜色，字体背景颜色
                                [{ 'font': [] }], // 字体
                                [{ 'align': [] }], // 对齐方式
                                ['clean'], // 清除文本格式
                                ['link', 'image'], // 链接、图片
                                ['code-block'],
                                ['blockquote'],
                            ],
                            handlers: {
                                'image': this.imageHandler
                            }
                        },
                    },
                    // 如果要图片拖拽功能，增加下面内容配置
                    imageDrop: true, // 拖动加载图片组件
                    imageResize: { // 图片缩放功能
                        displayStyles: {
                            backgroundColor: 'black',
                            border: 'none',
                            color: 'white'
                        },
                        modules: ['Resize', 'DisplayStyles', 'Toolbar']
                    },
                },
            }
        },

        destroyed() {
            this.$store.commit('articleManage/setCurrentMenuId', null)
        },

        mounted() {
            // 判断是否登录,没有登录则跳转回首页
            if (!checkLogin()) {
                Utils.popUpMsg('warning', '请先登录！', 3000)
                this.$router.push('/')
                return
            }
            this.$store.commit('articleManage/setCurrentMenuId', 4)

            // 获取参数，当 articleId 存在时，表示编辑
            if (this.$route.query.articleId) {
                this.articleId = this.$route.query.articleId
                this.findArticleDetail()
            }
        },

        methods: {
            // 查询文章详情
            findArticleDetail() {
                this.pageLoading = Utils.loading('文章数据加载中...')

                let params = {
                    articleId: this.articleId,
                    userId: this.userInfo.id
                }

                getArticleDetail(params).then(res => {
                    this.pageLoading.close()
                    if (res.code === 200) {
                        this.details = res.data // 得到文章详情数据
                        this.showArticleContent(res.data)
                    }
                }).catch(err => {
                    this.pageLoading.close()
                })
            },

            // 回显文章内容
            showArticleContent(data) {
                this.classifyDialog.title = data.title
                this.classifyDialog.content = data.content
                this.classifyDialog.classifyId = data.classifyId
                this.classifyDialog.abstract = data.abstract
                this.classifyDialog.coverUrl = data.coverUrl
            },

			// 查询分类列表
			findClassifyList() {
				return new Promise((resolve, reject) => {
					this.pageLoading = Utils.loading('分类加载中...')

					getClassifyList().then(res => {
						this.pageLoading.close()
						if (res.code === 200) { 
							this.classifyList = res.data
							resolve(res)
						} else {
							Utils.popUpMsg('error', res.msg, 3000)
							reject(res)
						}
					}).catch(err => {
						this.pageLoading.close()
						reject(err)
					})
				})
			},

			// 展示文章分类编辑弹窗
			showClassifyDialog(type) {  
				this.classifyDialog.state = type
				this.openClassifyDialog()
			},

            // 关闭文章分类编辑弹窗
            cancelClassifyDialog () {
                this.dialogVisible = false
            },

			// 打开文章分类弹窗
			openClassifyDialog() { 
				if (!this.classifyDialog.title) {
                    Utils.popUpMsg('warning', '请输入文章标题！', 3000)
                    return
                }

                if (!this.classifyDialog.content) {
                    Utils.popUpMsg('warning', '请输入文章内容！', 3000)
                    return
                }

				this.findClassifyList().then(() => {
					this.dialogVisible = true
				})
			},

            // 参数都差不多，直接写一个获取参数的函数
            getQuerys() {
                let params = {
					classifyId: this.classifyDialog.classifyId,
					title: this.classifyDialog.title,
					abstract: this.classifyDialog.abstract,
					content: this.classifyDialog.content,
					state: this.classifyDialog.state,
                    coverUrl: this.classifyDialog.coverUrl
				}

                // 编辑文章的时候要传文章id
                if (this.articleId) {
                    params.articleId = this.articleId
                }

                return params
            },

            // 创建文章
            addArticle() {
                this.pageLoading = Utils.loading('正在创建文章...')
				addArticle(this.getQuerys()).then(res => { 
					this.pageLoading.close()
					if (res.code === 200) { 
						Utils.popUpMsg('success', res.msg, 1500)
                        this.classifyDialog.title = ''
                        this.classifyDialog.content = ''
                        this.classifyDialog.abstract = ''
                        this.classifyDialog.classifyId = ''
                        this.classifyDialog.coverUrl = ''
						this.cancelClassifyDialog()
					} else {
						Utils.popUpMsg('error', res.msg, 3000)
					}
				}).catch(err => { 
					this.pageLoading.close()
				})
            },

            // 编辑文章
            editArticle() {
                this.pageLoading = Utils.loading('文章修改中...')
                updateArticle(this.getQuerys()).then(res => {
                    this.pageLoading.close()
                    if (res.code === 200) {
                        Utils.popUpMsg('success', res.msg, 1500)
                        this.cancelClassifyDialog()
                    } else {
                        Utils.popUpMsg('error', res.msg, 3000)
                    }
                }).catch(err => { 
                    this.pageLoading.close()
                })
            },

            // 添加文章回调
            confirmClassifyDialog() {
                if (!this.classifyDialog.classifyId) {
                    Utils.popUpMsg('warning', '请选择文章分类！', 3000)
                    return
                }

				if (!this.classifyDialog.abstract) {
					Utils.popUpMsg('warning', '请输入文章摘要！', 3000)
					return
				}

                // 在这里判断一下，如果articleId存在，表示编辑
                if (!this.articleId) {
                    this.addArticle() // 添加文章
                } else {
                    this.editArticle() // 编辑文章
                }
            },

            // 点击编辑器图片图标的回调（选择文件）
            imageHandler() {
                const input = document.createElement('input')
                input.setAttribute('type', 'file')
                input.setAttribute('accept', 'image/*')
                input.click()
                input.onchange = () => {
                    const file = input.files[0]
                    if (/^image\//.test(file.type)) {
                        this.handleUploadImg(file)
                    } else {
                        console.error('File is not an image.')
                    }

                    // 清除输入以便下次选择文件时可以重新选择相同的文件。
                    input.value = ''
                }
            },

			// 编辑器图片上传
            handleUploadImg(file) {
			   	// 上传图片的参数
				const formData = new FormData()
				formData.append('file', file)

				uploadFile(formData).then(res => {
					const url = process.env.VUE_APP_IMG_BASE_API + res.data.url // 从响应中获取图片URL。根据实际情况调整字段名。
                    const range = this.$refs.myQuillEditor.quill.getSelection() // 获取当前光标位置。
					// 在当前光标位置插入图片。可以根据需要调整index。例如，你也可以使用range.index +
                    this.$refs.myQuillEditor.quill.insertEmbed(range.index, 'image', url)
				})
            },

            onEditorBlur(quill) {
                // console.log('editor blur!', quill)
            },

            onEditorFocus(quill) {
                // console.log('editor focus!', quill)
            },

            onEditorReady(quill) {
                // console.log('editor ready!', quill)
            },

            // 内容改变时
            onEditorChange({ quill, html, text }) {
                this.previewHtml = html
            }
        }
    }
</script>

<style lang="scss" scoped>
    @media screen and (max-width: 750px) {
        .vanish_items {
            display: none;
        }

        .leaveSpace {
            padding-left: 0;
            padding-right: 0;
        }
    }

    @media screen and (min-width: 750px) {
        .appear_items {
            display: none;
        }

        .leaveSpace {
            padding-left: 10px;
            padding-right: 10px;
        }
    }

    .title::placeholder {
        font-size: 22px;
        color: #bcbcbc;
    }

    .title {
        font-size: 24px;
        width: 75%;
        height: 80px;
    }

    .draft:hover {
        cursor: pointer;
    }

    .publish:hover {
        cursor: pointer;
    }

    .editor {
        border: none !important;
    }

    .editor img {
        max-height: 30%;
        width: auto;
    }
</style>
